package summer.hot100.v1;

import java.util.*;

public class Solution200 {
    public int numIslands(char[][] grid) {
        int m = grid.length;
        int n = grid[0].length;
        boolean[][] used = new boolean[m][n];
        int res = 0;
        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                if (!used[i][j] && grid[i][j] == '1') {
                    dfs(used, i, j, grid);
                    res++;
                }
            }
        }
        return res;
    }

    public void dfs(boolean[][] used, int i, int j, char[][] grid) {
        if (i < 0 || i >= grid.length || j < 0 || j >= grid[0].length) return;
        if (used[i][j] || grid[i][j] != '1') return;
        used[i][j] = true;
        dfs(used, i + 1, j, grid);
        dfs(used, i - 1, j, grid);
        dfs(used, i, j + 1, grid);
        dfs(used, i, j - 1, grid);
    }
}
